import { createApp } from 'vue';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import App from './App.vue';
import router from './router';
import '@/assets/styles/global.css';
import axios from 'axios';

// 配置axios
axios.defaults.baseURL = 'http://localhost:8080';
axios.defaults.timeout = 5000;
axios.defaults.withCredentials = true;

// 添加请求拦截器
axios.interceptors.request.use(
  config => {
    const userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
      const user = JSON.parse(userInfo);
      config.headers.Authorization = `Bearer ${user.token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response && error.response.status === 403) {
      const userInfo = localStorage.getItem('userInfo');
      if (userInfo) {
        // token可能过期，清除用户信息并跳转到登录页
        localStorage.removeItem('userInfo');
        router.push('/login');
      }
    }
    return Promise.reject(error);
  }
);

// 全局挂载axios
const app = createApp(App);
app.config.globalProperties.$axios = axios;
app.use(ElementPlus);
app.use(router);
app.mount('#app');